package com.yylending.las.common.location;

import android.content.Context;
import android.text.TextUtils;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.yyfax.common.CLog;
import com.yylending.las.YJKD;
import com.yylending.las.common.location.entity.Address;
import com.yylending.las.common.location.entity.Location;

/**
 * 定位Service
 * Created by laixj on 2016/11/18.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class LocationService implements AMapLocationListener {
	private final static String TAG = "LocationPresenter";

	private AMapLocationClient mClient = null;
	private AMapLocationClientOption mOption;
	private Object objLock = new Object();
	//private ArrayList<LocationListener> mListenerList = new ArrayList<>();
	private LocationListener mListener;

	/***
	 * @param locationContext
	 */
	public LocationService(Context locationContext) {
		synchronized (objLock) {
			if (mClient == null) {
				mClient = new AMapLocationClient(locationContext);
				mClient.setLocationOption(getDefaultOption());
				mClient.setLocationListener(this);
				CLog.i(TAG, "LocationService 初始化");
			}
		}
	}

	/***
	 * @param listener
	 * @return
	 */

	public boolean registerListener(LocationListener listener) {
		boolean isSuccess = false;
		if (listener != null) {
			mListener = listener;
			CLog.i(TAG, "LocationService registerListener---");
		}
		return isSuccess;
	}

	public void unregisterListener(LocationListener listener) {
		mListener = null;
		CLog.i(TAG, "LocationService unregisterListener---");
	}

	/***
	 * @return DefaultLocationClientOption
	 */
	private AMapLocationClientOption getDefaultOption() {
		if (mOption == null) {
			mOption = new AMapLocationClientOption();
			mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
			//获取一次定位结果：
			//该方法默认为false。
			mOption.setOnceLocation(true);
			//获取最近3s内精度最高的一次定位结果：
			//设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
			mOption.setOnceLocationLatest(true);
			//设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
			mOption.setInterval(1000);
			//设置是否返回地址信息（默认返回地址信息）
			mOption.setNeedAddress(true);
			//设置是否强制刷新WIFI，默认为true，强制刷新。
			mOption.setWifiActiveScan(false);
			//设置是否允许模拟位置,默认为false，不允许模拟位置
			mOption.setMockEnable(false);
			//单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
			mOption.setHttpTimeOut(30000);
			//关闭缓存机制
			mOption.setLocationCacheEnable(false);
		}
		return mOption;
	}

	public void startLocation() {
		synchronized (objLock) {
			CLog.i(TAG, "LocationService startLocation mClient != null---" + (mClient != null));
			if (mClient != null) {
				stopLocation();
				CLog.i(TAG, "LocationService startLocation--111--");
				mClient.startLocation();
			}else{
				notifyFailure(false, true);
				YJKD.getInstance().initLocationService();
			}
		}
	}

	public void stopLocation() {
		if (mClient != null) {
			CLog.i(TAG, "LocationService stopLocation---");
			mClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
		}
	}

	public void releaseLocation() {
		if (mClient != null) {
			CLog.i(TAG, "LocationService releaseLocation---");
			mClient.stopLocation();
			mClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
			mClient = null;
		}
	}

	@Override
	public void onLocationChanged(AMapLocation location) {
		CLog.i(TAG, "获取定位信息返回");
		if (location != null) {
			if (location.getErrorCode() == 0) {
				CLog.i(TAG, "获取定位信息成功, ErrCode=" + location.getErrorCode());
				//可在其中解析amapLocation获取相应内容。
				handleLocationInfo(location);
			} else {
				//定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
				CLog.i(TAG, "获取定位信息失败, ErrCode=" + location.getErrorCode());
				CLog.i(TAG, "获取定位信息失败, errorInfo=" + location.getErrorInfo());
				boolean noPermission = false;
				boolean needRetry = false;
				if(location.getErrorCode() == 12){// ||(location.getErrorCode() == 13 && Constants.isConnected)
					noPermission = true;
				}else if(location.getErrorCode() == 10){//需重新初始化定位
					needRetry = true;
					releaseLocation();
					YJKD.getInstance().initLocationService();
				}
				notifyFailure(noPermission, needRetry);
			}
		}
	}

	private void notifyFailure(boolean noPermission, boolean needRetry) {
		if (null != mListener) {
			CLog.i(TAG, "获取定位信息失败, notifyFailure");
			mListener.onLocateFailure(noPermission, needRetry);
		}
	}

	private void notifySuccess(Location location) {
		if (null != mListener) {
			mListener.onLocateSuccess(location);
		}
	}

	private void handleLocationInfo(AMapLocation location) {
		CLog.i(TAG, "定位返回：Latitude=" + location.getLatitude() + "; Longitude=" + location.getLongitude()
				+ "; Province=" + location.getProvince() + "; City=" + location.getCity());
		if (TextUtils.isEmpty(location.getProvince()) || TextUtils.isEmpty(location.getCity())) {
			notifyFailure(false, false);
		} else {
			Location newLocation = new Location(location.getLatitude(), location.getLongitude());
			newLocation.lastTime = System.currentTimeMillis();
			newLocation.address = new Address(location.getProvince(), location.getCity(), location.getDistrict());
			notifySuccess(newLocation);
		}
	}
}